package main

import "fmt"

type Hub struct {
	clients    map[*Client]bool
	broadcast  chan []byte
	register   chan *Client
	unregister chan *Client
}

func newHub() *Hub {
	return &Hub{
		clients:    make(map[*Client]bool),
		broadcast:  make(chan []byte),
		register:   make(chan *Client),
		unregister: make(chan *Client),
	}
}

// 维护hub结构体各个属性的数据处理
func (h *Hub) run() {
	for {
		fmt.Println("hub run start")
		select {
		case client := <-h.register: // client注册
			h.clients[client] = true
			fmt.Println("hub client register: ", client)
		case client := <-h.unregister: // client注销
			fmt.Println("hub unregister client: ", client)
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				close(client.send)
			}

		case message := <-h.broadcast: // message广播到所有client
			fmt.Println("hub 广播信息: ", message)
			for client := range h.clients {
				select {
				case client.send <- message:
				default:
					close(client.send)
					delete(h.clients, client)
				}
			}
		}
	}
}
